package com.dminvoicemanager.printdoc;

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.printdoc.DM_Print_StockLoading_Active;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_List_Expand_Helper;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_Print_StockLoading_Active extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	SQLiteDatabase mydb;
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private String LOGPRINTSTRING = "FInvLogPrint";
	private String USER_SETTINGS = "usersettings";
	String currentRefNo;
	TextView printrefno, printdate, printloadfrom, printloadto, printtotcases,
			printtotpieces, printtotvalue;
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", stLoadDate, loadFrom, LoadTo;
	double totCases = 0.0, totPieces = 0.0, totAmount = 0.0;
	String currentIndex, CurrentStringPrint;
	BluetoothAdapter mBTAdapter;
	BluetoothSocket mBTSocket = null;
	Dialog dialogProgress;
	String BILL, TRANS_ID, CurrentUser;
	String PRINTER_MAC_ID;
	final String ERROR_MESSAGE = "There has been an error in printing the bill.";
	String Heading_a = "\r\n";
	String Heading_b = "";
	String Heading_c = "";
	String Heading_d = "";

	int loopPrint = 0, logPrint = 0 ,countStl;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void PrintCurrentview(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_Print_StockLoading_Active.class);
		myIntent.putExtra("TAGIDREFNO", currentRefNo);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
	}

	DecimalFormat formatValues = new DecimalFormat("#,###.00");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_transaction_doc_stloading);
		Bundle bundle = getIntent().getExtras();
		currentRefNo = bundle.getString("TAGIDREFNO");

		printrefno = (TextView) findViewById(R.id.printrefno);
		printdate = (TextView) findViewById(R.id.printdate);
		printloadfrom = (TextView) findViewById(R.id.printloadfrom);
		printloadto = (TextView) findViewById(R.id.printloadto);
		printtotcases = (TextView) findViewById(R.id.printtotcases);
		printtotpieces = (TextView) findViewById(R.id.printtotpieces);
		printtotvalue = (TextView) findViewById(R.id.printtotvalue);
		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Stock Loading");
		TextView printpreviewtitle = (TextView) findViewById(R.id.printpreviewtitle);
		printpreviewtitle.setText("Stock Loading");

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		mydb.execSQL("DROP TABLE IF EXISTS FInvLogPrint");

		mydb.execSQL("create table if not exists "
				+ LOGPRINTSTRING
				+ "(print_id integer primary key autoincrement,printArray text not null);");
		selectCurrentPrinter();
		printSummary();
		PrintListStockLoading();
	}

	private void selectCurrentPrinter() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		try {
			curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (curUserSettings != null) {
			if (curUserSettings.getCount() > 0) {
				while (curUserSettings.moveToNext()) {
					CurrentUser = curUserSettings.getString(1);
					PRINTER_MAC_ID = curUserSettings.getString(8);
				}
			}
		}
	}

	private void printSummary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdessum = null;
		try {
			String query = "SELECT * fROM frepStockLoadingSummary WHERE tempRepStLoadRefNo ='"
					+ currentRefNo + "'";
			allrowitemsdessum = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowitemsdessum != null) {
			if (allrowitemsdessum.getCount() > 0) {
				while (allrowitemsdessum.moveToNext()) {
					stLoadDate = allrowitemsdessum.getString(9);
					String fromloc = allrowitemsdessum.getString(10);
					String toloc = allrowitemsdessum.getString(11);
					String[] loadFromAr = fromloc.split("/");
					loadFrom = loadFromAr[1]; // invcuscode
					String[] loadToAr = toloc.split("/");
					LoadTo = loadToAr[1]; // invcusname

				}
			}
		}
	}

	private void PrintListStockLoading() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3" };

		int[] totrdes = new int[] { R.id.print_item1, R.id.print_item2,
				R.id.print_item3 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor allrowitemsdes = null;
		try {
			String query = "SELECT LH.RefNo,LD.CaseQty,LD.PiceQty,LD.Amt,LD.LitemName,LD.RefNo,LH.TxnDate,LD.SeqNo FROM fLoadhed LH,fLoadDet LD WHERE LD.RefNo = LH.RefNo AND  LH.RefNo ='"
					+ currentRefNo + "' AND RecordChecked = '99' order by LD.SeqNo ASC";

			// String query = "SELECT * FROM fLoadDet";
			allrowitemsdes = mydb.rawQuery(query, null);
			if (allrowitemsdes != null) {
				if (allrowitemsdes.getCount() > 0) {
					while (allrowitemsdes.moveToNext()) {
						Log.v(TAG, "POSITIVE");

						// **********Printing**********
						logPrint = logPrint + 1;
						// PRINTER_MAC_ID = "AC:3F:A4:12:D7:E8";
						// PRINTER_MAC_ID = "00:22:58:3A:C6:49";
						// **********Printing**********
						if (logPrint == 1) {
							Heading_a = "\r\n" + "          "
									+ "Maliban Biscuits(Pvt) Ltd." + "\r\n"
									+ "       "
									+ "389,Galle road,Ratmalana,Sri Lanka."
									+ "\r\n" + "              "
									+ "Tel: 011 5 555000" + "\r\n"
									+ "                   "
									+ "Stock Loading\r\n\n";
						}
						// **********Printing End**********
						// totCases =0.0, totPieces =0.0, totAmount =0.0;
						String StrPrintRefNo = allrowitemsdes.getString(0);
						String StrPrintCaseQty = allrowitemsdes.getString(1);
						Double StrPrintCaseQtyVal = Double
								.parseDouble(StrPrintCaseQty);
						totCases = totCases + StrPrintCaseQtyVal;
						String StrPrintPiceQty = allrowitemsdes.getString(2);
						Double StrPrintPiceQtyVal = Double
								.parseDouble(StrPrintPiceQty);
						totPieces = totPieces + StrPrintPiceQtyVal;
						String StrPrintTotalAmt = allrowitemsdes.getString(3);
						Double StrPrintTotalAmtVal = Double
								.parseDouble(StrPrintTotalAmt);
						StrPrintTotalAmtVal = Math.round(StrPrintTotalAmtVal * 100) / 100.0d;
						totAmount = totAmount + StrPrintTotalAmtVal;
						String StrPrintLitemName = allrowitemsdes.getString(4);
						String SeqNo = allrowitemsdes.getString(7);
						Log.v(TAG, "Seq No :"+ SeqNo);
						countStl = countStl + 1;
						String countStlindex = Integer.toString(countStl);
						// **********Printing**********
						String printFormatSpaceHeading = "                    ";
						String subTitlea = "Ref No" + printFormatSpaceHeading;
						String subTitleaPrint = subTitlea.substring(0,
								Math.min(16, subTitlea.length()));
						String subTitleb = "Date" + printFormatSpaceHeading;
						String subTitlebPrint = subTitleb.substring(0,
								Math.min(16, subTitleb.length()));
						String subTitlec = "Loading From"
								+ printFormatSpaceHeading;
						String subTitlecPrint = subTitlec.substring(0,
								Math.min(16, subTitlec.length()));
						String subTitled = "Loading To"
								+ printFormatSpaceHeading;
						String subTitledPrint = subTitled.substring(0,
								Math.min(16, subTitled.length()));

						String title_a = "\r\n" + subTitleaPrint + ":"
								+ currentRefNo;
						String title_b = "\r\n" + subTitlebPrint + ":"
								+ stLoadDate;
						String title_c = "\r\n" + subTitlecPrint + ":"
								+ loadFrom;
						String title_d = "\r\n" + subTitledPrint + ":" + LoadTo;
						String title_e = "\r\n--------------------------------------------";              
						String title_f ="             (CS/PS)   (Rs)";
						String title_g = "\r\n                   " + title_f;
						String title_h = "\r\n--------------------------------------------";

						if (logPrint == 1) {
							Heading_b = "\r\n\n" + title_a + title_b + title_c
									+ title_d + title_e + title_g + title_h;
						}

						// **********Printing End**********
						
						String printSpaceName ="                    ";
						StrPrintLitemName = StrPrintLitemName + printSpaceName;
						String PrintStrPrintLitemName = StrPrintLitemName.substring(0,Math.min(24,StrPrintLitemName.length()));

						String itemCasePieces = printSpaceName + StrPrintCaseQty +"/"+StrPrintPiceQty;
						String PrintitemCasePiecesQty = itemCasePieces.substring(Math.max(itemCasePieces.length() - 8, 0));

						StrPrintTotalAmt = printSpaceName + StrPrintTotalAmt;
						String PrintStrPrintTotalAmt = StrPrintTotalAmt.substring(Math.max(StrPrintTotalAmt.length() - 12, 0));
						
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_1", PrintStrPrintLitemName);
						maptrdes.put("item_result_2", PrintitemCasePiecesQty);
						maptrdes.put("item_result_3", PrintStrPrintTotalAmt);

						String StrSeqNo =  countStlindex + printSpaceName;
						StrSeqNo = StrSeqNo.substring(0,Math.min(2,StrSeqNo.length()));
						Log.v(TAG, "StrSeqNo :"+StrSeqNo);
						Heading_c = "\r\n" + StrSeqNo + "."
								+ PrintStrPrintLitemName + PrintitemCasePiecesQty + PrintStrPrintTotalAmt;

						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_transaction_doc_stloading_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);

						Cursor getprintString = null;
						try {
							String queryPStr = "SELECT * from FInvLogPrint";
							getprintString = mydb.rawQuery(queryPStr, null);
							if (getprintString.getCount() > 0) {
								while (getprintString.moveToNext()) {
									currentIndex = getprintString.getString(0);
									CurrentStringPrint = getprintString
											.getString(1);

									String updatingArray = "\r\n"
											+ CurrentStringPrint + Heading_a
											+ Heading_b + Heading_c;

									ContentValues savePrintArrayUpdate = new ContentValues();
									savePrintArrayUpdate.put("printArray",
											updatingArray);
									mydb.update(LOGPRINTSTRING,
											savePrintArrayUpdate, "print_id ='"
													+ currentIndex + "'", null);
									Heading_a = "";
									Heading_b = "";
									Heading_c = "";
								}
							} else {
								ContentValues savePrintArray = new ContentValues();
								String saveArray = Heading_a + Heading_b
										+ Heading_c;
								savePrintArray.put("printArray", saveArray);
								mydb.insert(LOGPRINTSTRING, null,
										savePrintArray);
								Heading_a = "";
								Heading_b = "";
								Heading_c = "";
							}
						} catch (Exception e) {
						}
					}
				} else {
					Log.v(TAG, "NEGATIVE");
				}
			}

		} catch (Exception e) {
		}
		// printrefno;printdate;printloadfrom;printloadto;printtotcases;printtotpieces;printtotvalue
		int totCasesi = (int) totCases;
		int totPiecesi = (int) totPieces;
		String printtotCases = Integer.toString(totCasesi);
		String printtotPieces = Integer.toString(totPiecesi);
		String totAmountStr = formatValues.format(totAmount);
		// String printtotAmount = Double.toString(totAmount);

		String title_i = "\r\n--------------------------------------------";
		Heading_d = "\r\nTotal Quantity :" + "       " + printtotCases
				+ "     " + printtotPieces + "    " + totAmountStr;
		String title_j = "\r\n\n\nSignature    		: 				";
		String buttomRaw = title_i + Heading_d + title_j;

		Cursor getprintSummary = null;
		try {
			String queryPStr = "SELECT * from FInvLogPrint";
			getprintSummary = mydb.rawQuery(queryPStr, null);
			if (getprintSummary.getCount() > 0) {
				while (getprintSummary.moveToNext()) {
					currentIndex = getprintSummary.getString(0);
					CurrentStringPrint = getprintSummary.getString(1);

					String updatingArray = "\r\n"
							+ CurrentStringPrint
							+ buttomRaw
							+ "\r\n\n--------------------------------------------";

					ContentValues savePrintArrayUpdate = new ContentValues();
					savePrintArrayUpdate.put("printArray", updatingArray);
					mydb.update(LOGPRINTSTRING, savePrintArrayUpdate,
							"print_id ='" + currentIndex + "'", null);
				}
			}

		} catch (Exception e) {
		}
		printrefno.setText(currentRefNo);
		printdate.setText(stLoadDate);
		printloadfrom.setText(loadFrom);
		printloadto.setText(LoadTo);
		printtotcases.setText(printtotCases);
		printtotpieces.setText(printtotPieces);
		printtotvalue.setText(totAmountStr);

		callPrintDevice();
		allrowitemsdes.close();
		mydb.close();
		DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}

	private void callPrintDevice() {
		// TODO Auto-generated method stub
		// PRINTER_MAC_ID = "AC:3F:A4:12:D7:E8";
		// PRINTER_MAC_ID = "00:22:58:3A:C6:49";
		Cursor getprintString = null;
		try {
			String queryPStr = "SELECT * from FInvLogPrint";
			getprintString = mydb.rawQuery(queryPStr, null);
			if (getprintString.getCount() > 0) {
				while (getprintString.moveToNext()) {
					CurrentStringPrint = getprintString.getString(1);
					BILL = CurrentStringPrint;
					mBTAdapter = BluetoothAdapter.getDefaultAdapter();
					dialogProgress = new Dialog(
							DM_Print_StockLoading_Active.this);

					try {
						if (mBTAdapter.isDiscovering())
							mBTAdapter.cancelDiscovery();
						else
							mBTAdapter.startDiscovery();
					} catch (Exception e) {
						Log.e("Class ", "My Exe ", e);
					}
					System.out.println("BT Searching status :"
							+ mBTAdapter.isDiscovering());
					if (mBTAdapter == null) {
						Toast.makeText(this,
								"Device has no bluetooth capability",
								Toast.LENGTH_LONG).show();
						finish();
					} else {
						if (!mBTAdapter.isEnabled()) {
							Intent i = new Intent(
									BluetoothAdapter.ACTION_REQUEST_ENABLE);
							startActivityForResult(i, 0);
						}

						// Register the BroadcastReceiver
						IntentFilter filter = new IntentFilter(
								BluetoothDevice.ACTION_FOUND);
						registerReceiver(mReceiver, filter); // Don't forget to
																// unregister
																// during
																// onDestroy
						dialogProgress.setTitle("Finding printer...");
						dialogProgress
								.setOnDismissListener(new DialogInterface.OnDismissListener() {
									public void onDismiss(DialogInterface dialog) {
										dialog.dismiss();
										setResult(RESULT_CANCELED);
										finish();
									}
								});
						dialogProgress.show();

					}

				}
			}
		} catch (Exception e) {
		}

	}

	public void printBillToDevice(final String address) {
		new Thread(new Runnable() {

			public void run() {
				runOnUiThread(new Runnable() {

					public void run() {
						dialogProgress.setTitle("Connecting...");
						dialogProgress.show();
					}

				});

				mBTAdapter.cancelDiscovery();

				try {
					BluetoothDevice mdevice = mBTAdapter
							.getRemoteDevice(address);
					Method m = mdevice.getClass().getMethod(
							"createRfcommSocket", new Class[] { int.class });
					mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);

					mBTSocket.connect();
					OutputStream os = mBTSocket.getOutputStream();
					os.flush();

					os.write(BILL.getBytes());
					System.out.println(BILL);

					if (mBTAdapter != null)
						mBTAdapter.cancelDiscovery();
					setResult(RESULT_OK);
					finish();
				} catch (Exception e) {
					Log.e("Class ", "My Exe ", e);
					// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
					// Toast.LENGTH_SHORT).show();
					e.printStackTrace();
					setResult(RESULT_CANCELED);
					finish();

				}

				runOnUiThread(new Runnable() {

					public void run() {
						try {
							dialogProgress.dismiss();
						} catch (Exception e) {
							Log.e("Class ", "My Exe ", e);
						}
					}

				});

			}

		}).start();
	}

	@Override
	protected void onDestroy() {
		Log.i("Dest ", "Checking Ddest");
		super.onDestroy();
		try {
			if (dialogProgress != null)
				dialogProgress.dismiss();
			if (mBTAdapter != null)
				mBTAdapter.cancelDiscovery();
			this.unregisterReceiver(mReceiver);
		} catch (Exception e) {
			Log.e("Class ", "My Exe ", e);
		}
	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			try {
				String action = intent.getAction();
				// When discovery finds a device
				if (BluetoothDevice.ACTION_FOUND.equals(action)) {
					// Get the BluetoothDevice object from the Intent
					BluetoothDevice device = intent
							.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					System.out.println("***" + device.getName() + " : "
							+ device.getAddress());

					if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
						mBTAdapter.cancelDiscovery();
						dialogProgress.dismiss();
						/*
						 * Toast.makeText(DM_Print_StockLoading_Active.this,
						 * device.getName() + " Printing data",
						 * Toast.LENGTH_LONG).show();
						 */
						printBillToDevice(PRINTER_MAC_ID);
						/*
						 * Toast.makeText(DM_Print_StockLoading_Active.this,
						 * device.getName() + " found", Toast.LENGTH_LONG)
						 * .show();
						 */
					}
				}
			} catch (Exception e) {
				Log.e("Class  ", "My Exe ", e);
				// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
				// Toast.LENGTH_SHORT).show();

			}
		}
	};

	@Override
	public void onBackPressed() {
		try {
			if (mBTAdapter != null)
				mBTAdapter.cancelDiscovery();
			this.unregisterReceiver(mReceiver);
		} catch (Exception e) {
			Log.e("Class ", "My Exe ", e);
		}
		setResult(RESULT_CANCELED);
		finish();
	}

}
